package de.wiroo.setup.web.common;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;

import de.stefanocke.roo.wicket.RooStereotype;

@RooStereotype("wicket.AnnotationUtils")
public class AnnotationUtils {
	@RooStereotype("wicket.AnnotationUtils.getAnnotations")
	public static AnnotationMap getAnnotations(Class<?> modelClass, Class<?> fieldsClass, String fieldName,
			String modelClassFieldName) {
		try {
			Map<Class<? extends Annotation>, Annotation> map = new HashMap<Class<? extends Annotation>, Annotation>();
			Annotation[] annotations = fieldsClass.getDeclaredField(fieldName).getAnnotations();
			for (int i = 0; i < annotations.length; i++) {
				map.put(annotations[i].annotationType(), annotations[i]);
			}

			if (modelClassFieldName != null) {
				annotations = modelClass.getDeclaredField(modelClassFieldName).getAnnotations();
				for (int i = 0; i < annotations.length; i++) {
					if (!map.containsKey(annotations[i].annotationType())) {
						map.put(annotations[i].annotationType(), annotations[i]);
					}
				}
			}
			return new AnnotationMap(map);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static class AnnotationMap {
		private Map<Class<? extends Annotation>, Annotation> map;

		private AnnotationMap(Map<Class<? extends Annotation>, Annotation> map) {
			this.map = new HashMap<Class<? extends Annotation>, Annotation>(map);
		}

		@SuppressWarnings("unchecked")
		public <A extends Annotation> A get(Class<? extends A> annotationClass) {
			return (A) map.get(annotationClass);
		}
		
		public <A extends Annotation> boolean contains(Class<? extends A> annotationClass){
			return map.containsKey(annotationClass);
		}
	}
}
